//=================================================
// NABTON Client: scale.ino
// 2015-01-17
// Version 0.1
//=================================================
//==================================================
// Misc
//==================================================
int signal = 10;
int g_sid = 6;
float factor = 85.8/(3431-1472);
#define PIN_MSG 3
#define NABTON_DATA 1
#define NABTON_DATA_ACK 2
//=================================================
void sendNDS(int sid, float data)
//=================================================
{
  //Serial.print(":"); //start
  Serial.print(NABTON_DATA);
  Serial.print(" "); 
  Serial.print(sid);
  Serial.print(" "); 
  Serial.print(data);
  Serial.print(";"); // End
  Serial.flush();
}
//=================================================
void blinkLed(int nn)
//=================================================
{
  digitalWrite(PIN_MSG,LOW);
  for(int i=0;i<nn;i++)
  { 
     digitalWrite(PIN_MSG,HIGH);
     delay(100);
     digitalWrite(PIN_MSG,LOW);
     delay(100);
  }  
}
//=================================================
void recACK()
//=================================================
{
  int nx = Serial.available();
  if (nx > 0) 
  {
        blinkLed(1);
  }
}
//=================================================
void setup() 
//=================================================
{
  Serial.begin(9600);
  pinMode(signal, INPUT);
  pinMode(8, OUTPUT);
  pinMode(PIN_MSG, OUTPUT);
  digitalWrite(PIN_MSG,LOW);
}

int value = HIGH;
int count = 0;
float oldw[10];
float sum,ftemp;
int ready = 0;
//=================================================
void loop() {
//=================================================
  int i;
  value = digitalRead(signal);
  if(value == LOW)
  {
    count++;
  }
  if(count > 0 && value == HIGH)
  {
     for(i=5;i>0;i--)oldw[i] = oldw[i-1];
     oldw[0]=(count-1472)*factor;
     ftemp = 0.0;
     sum = 0.0;
     for(i=0;i<5;i++)
     {
       ftemp = ftemp + (oldw[i] - oldw[i+1])*(oldw[i] - oldw[i+1]);
     }
     for(i=0;i<=5;i++)
     {
       sum = sum + oldw[i];
     }
     sum = sum/6;
     if(ftemp < 0.02 && sum > 10.0 && sum < 100.)
     {
       //Serial.print("Your weight is (kg): ");
       //Serial.print(ftemp);
       //Serial.print("  ");
       sendNDS(g_sid,sum);
       //Serial.println(sum);
       digitalWrite(8,HIGH);
       delay(60000);
       digitalWrite(8,LOW);
       //Serial.println("Ready for new measurement");
     }

     /*Serial.print(count);
     Serial.print("  ");
     Serial.print(ftemp);
     Serial.print("  ");
     Serial.println(sum);*/
     count = 0;
  }
  //Serial.println(value);
  //delayMicroseconds(1); 
}


